<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-calendar"></i> 新生基本信息管理
        </el-breadcrumb-item>
        <el-breadcrumb-item>新生编辑</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="form-box">
        <el-form
          ref="formRef"
          :rules="rules"
          :model="form.data"
          status-icon
          label-width="80px"
        >
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="form.data.studentName" clearable></el-input>
          </el-form-item>
          <el-form-item label="身份证号" prop="idCardNo">
            <el-input
              v-model="form.data.idCardNo"
              maxlength="18"
              minlength="15"
              placeholder="输入身份证"
              show-word-limit
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobilePhone">
            <el-input
              v-model="form.data.mobilePhone"
              maxlength="11"
              show-word-limit
              autocomplete="off"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.data.gender" placeholder="请选择性别">
              <el-option key="男" label="男" value="男"></el-option>
              <el-option key="女" label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="出生日期" prop="birth">-->
          <!--            <el-date-picker-->
          <!--              v-model="form.data.birth"-->
          <!--              type="date"-->
          <!--              placeholder="选择一个日期"-->
          <!--              format="YYYY-MM-DD"-->
          <!--              value-format="YYYY-MM-DD"-->
          <!--            ></el-date-picker>-->
          <!--          </el-form-item>-->
          <el-form-item label="民族" prop="nation">
            <el-input v-model="form.data.nation" clearable></el-input>
          </el-form-item>
          <!-- <el-form-item label="年级" prop="grade">
            <el-input
              v-model="form.data.grade"
              maxlength="4"
              placeholder="输入年级"
              show-word-limit
            ></el-input>
          </el-form-item> -->
          <el-form-item label="政治面貌" prop="political">
            <!-- <el-input v-model="form.data.political"></el-input> -->
            <el-select 
              v-model="form.data.political"
              placeholder="请选择政治面貌"
            >
              <el-option key="团员" label="团员" value="团员"></el-option>
              <el-option key="群众" label="群众" value="群众"></el-option>
              <el-option key="党员" label="党员" value="党员"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="婚姻状况" prop="marital">
            <el-select v-model="form.data.marital" placeholder="请选择婚姻状况">
              <el-option key="未婚" label="未婚" value="未婚"></el-option>
              <el-option key="已婚" label="已婚" value="已婚"></el-option>
              <el-option key="离异" label="离异" value="离异"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="籍贯（省）" prop="domicilePlaceProvince">
            <el-input v-model="form.data.domicilePlaceProvince" clearable></el-input>
          </el-form-item>
          <el-form-item label="籍贯（市）" prop="domicilePlaceCity">
            <el-input v-model="form.data.domicilePlaceCity" clearable></el-input>
          </el-form-item>

          <el-form-item label="户籍地址" prop="domicilePlaceAddress">
            <el-input v-model="form.data.domicilePlaceAddress" clearable></el-input>
          </el-form-item>
          <el-form-item label="居住地址" prop="presentAddress">
            <el-input v-model="form.data.presentAddress" clearable></el-input>
          </el-form-item>
          <!--          <el-form-item label="电子邮件" prop="email">-->
          <!--            <el-input v-model="form.data.email" type="email" clearable></el-input>-->
          <!--          </el-form-item>-->
          <el-form-item label="所属学院" prop="collegeName" >
            <el-select
              v-model="form.data.collegeId"
              placeholder="请选择学院"
              @change="getMajorList"
            >
              <el-option
                v-for="item in collegeList"
                :key="item.sid"
                :label="item.collegeName"
                :value="item.sid"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属专业" prop="majorName">
            <el-select v-model="form.data.majorId" placeholder="请选择专业">
              <el-option
                v-for="item in majorList"
                :key="item.sid"
                :label="item.majorName"
                :value="item.sid"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import request from "../../utils/request";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
export default {
  name: "AddNew",

  setup() {
    // 身份证号码验证
    const validateCardID = (rule, value, callback) => {
      if (value == "") {
        return callback(new Error("身份证号不能为空"));
      } else if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
        callback(new Error("你输入的身份证长度或格式错误"));
      }
      //身份证城市
      var aCity = {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "台湾",
        81: "香港",
        82: "澳门",
        91: "国外",
      };
      if (!aCity[parseInt(value.substr(0, 2))]) {
        callback(new Error("你的身份证地区非法"));
      }

      // 出生日期验证
      var sBirthday = (
          value.substr(6, 4) +
          "-" +
          Number(value.substr(10, 2)) +
          "-" +
          Number(value.substr(12, 2))
        ).replace(/-/g, "/"),
        d = new Date(sBirthday);
      if (
        sBirthday !=
        d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate()
      ) {
        callback(new Error("身份证上的出生日期非法"));
      }

      // 身份证号码校验
      var sum = 0,
        weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
        codes = "10X98765432";
      for (var i = 0; i < value.length - 1; i++) {
        sum += value[i] * weights[i];
      }
      var last = codes[sum % 11]; //计算出来的最后一位身份证号码
      if (value[value.length - 1] != last) {
        callback(new Error("你输入的身份证号非法"));
      }
      callback();
    };
    //验证年级
    const validateGrade = (rule, value, callback) => {
      if (value == "") {
        return callback(new Error("年级不能为空"));
      } else if (!/^[0-9]{4}$/.test(value)) {
        callback(new Error("你输入的年级长度或格式错误"));
      }
    };
    // 手机号校验
    const validatePhone = (rule, value, callback) => {
      const reg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确的电话号码"));
      }
       
    };
    const rules = {
      studentName: [{required: true, message: "请输入用户名", trigger: "blur"}],
      idCardNo: [{validator: validateCardID, trigger: "blur"}],
      grade: [{validator: validateGrade, trigger: "blur"}],
      domicilePlaceProvince: [{required: true, message: "请输入省份", trigger: "blur"}],
    };
    const router = useRouter();
    const route = useRoute();
    const store = useStore();

    const collegeList = ref([]);
    request.get("/college").then((res) => {
      collegeList.value = res.data;
    });

    const majorList = ref([]);
    const getMajorList = (val) => {
      console.log(val);
      form.data.majorId = "";
      request.get("/major/byCollegeId?collegeId=" + val).then((res) => {
        majorList.value = res.data;
      });
    };

    const formRef = ref(null);
    var form = reactive({
      data: {
        sid: "",
      },
    });
    if (route.query.id) {
      request.get("/student/" + route.query.id).then((res) => {
        getMajorList(res.data.collegeId);
        form.data = res.data;
      });
    }
    // // 提交
    const onSubmit = () => {
      // 表单校验
      formRef.value.validate((valid) => {
        if (valid) {
          if (form.data.idCardNo.length < 15) {
            ElMessage.error("身份证输入错误");
          } else {
            var method = form.data.sid === "" ? "POST" : "PUT";
            request({
              url: "/student",
              method: method,
              data: form.data,
            }).then((res) => {
              if (res.code == 18) {
                ElMessage.error(res.msg);
              } else {
                ElMessage.success("提交成功！");
                // 关闭当前页面的标签页;
                store.commit("closeCurrentTag", {
                  $router: router,
                  $route: route,
                });
              }
              router.push("/admin/new");
            });
          }
        } else {
          return false;
        }
      });
    };
    // 重置
    const onReset = () => {
      formRef.value.resetFields();
    };

    return {
      collegeList,
      majorList,
      rules,
      formRef,
      form,
      onSubmit,
      onReset,
      getMajorList,
      validateCardID,
      validateGrade,
      validatePhone,
    };
  },
};
</script>